package jwcb.admin.server.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jwcb.admin.api.user.domain.dto.AppUserDTO;
import jwcb.admin.api.user.domain.dto.AppUserListReqDTO;
import jwcb.admin.api.user.domain.dto.UserEditReqDTO;
import jwcb.admin.server.user.config.RabbitConfig;
import jwcb.admin.server.user.domain.entity.AppUser;
import jwcb.admin.server.user.mapper.AppUserMapper;
import jwcb.admin.server.user.service.IAppUserService;
import jwcb.javapjframework.common.core.utils.AESUtil;
import jwcb.javapjframework.common.core.utils.BeanCopyUtil;
import jwcb.javapjframework.common.core.utils.StringUtil;
import jwcb.javapjframework.common.domain.domain.ResultCode;
import jwcb.javapjframework.common.domain.domain.dto.BasePageDTO;
import jwcb.javapjframework.common.domain.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class AppUserServiceImpl implements IAppUserService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${appuser.info.defaultAvatar}")
    private String defaultAvatar;
    @Autowired
    private AppUserMapper appUserMapper;
    /**
     * 根据微信注册用户
     * @param openId 用户微信ID
     * @return C端用户VO
     */
    @Override
    public AppUserDTO registerByOpenId(String openId) {
        if(StringUtil.isBlank(openId)) {
            throw new ServiceException("微信Id不能为空",ResultCode.INVALID_PARA.getCode());
        }
        AppUser appUser = new AppUser();
        appUser.setOpenId(openId);
        appUser.setNickName("user" + (int)(Math.random() * 9000) + 1000);
        appUser.setAvatar(defaultAvatar);
        appUserMapper.insert(appUser);
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser,appUserDTO);
        return appUserDTO;
    }


    /**
     * 根据OpenId查询用户
     * @param openId c端用户信息
     * @return 用户信息
     */
    @Override
    public AppUserDTO findByOpenId(String openId) {
        if(StringUtil.isBlank(openId)) {
            return null;
        }
        AppUser appUser = appUserMapper.selectOne(new LambdaQueryWrapper<AppUser>()
        .eq(AppUser::getOpenId, openId));
        if(appUser == null) {
            return null;
        }
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser,appUserDTO);
        // 手机号明文显示
        appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
        return appUserDTO;
    }


    /**
     * 根据手机号码注册用户
     * @param phone 手机号码
     * @return C端用户DTO
     */
    @Override
    public AppUserDTO registerByPhone(String phone) {
        if(StringUtil.isBlank(phone)) {
            throw new ServiceException("手机号码不能为空",ResultCode.INVALID_PARA.getCode());
        }
        AppUser appUser = new AppUser();
        appUser.setNickName("user" + (int)(Math.random() * 9000) + 1000);
        appUser.setAvatar(defaultAvatar);
        appUser.setPhoneNumber(AESUtil.encryptHex(phone));
        appUserMapper.insert(appUser);
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser,appUserDTO);
        return appUserDTO;
    }


    /**
     * 根据phone查询用户
     * @param phone c端用户信息
     * @return 用户信息
     */
    @Override
    public AppUserDTO findByPhone(String phone) {
        if(StringUtil.isBlank(phone)) {
            return null;
        }
        AppUser appUser = appUserMapper.selectOne(new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getPhoneNumber, AESUtil.encryptHex(phone)));
        if(appUser == null) {
            return null;
        }
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser,appUserDTO);
        // 手机号明文显示
        appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
        return appUserDTO;
    }

    @Override
    public void edit(UserEditReqDTO userEditReqDTO) {
        AppUser appUser = appUserMapper.selectById(userEditReqDTO.getUserId());
        if (appUser == null) {
            throw new ServiceException("用户不存在", ResultCode.INVALID_PARA.getCode());
        }
        appUser.setNickName(userEditReqDTO.getNickName());
        appUser.setAvatar(userEditReqDTO.getAvtar());
        appUserMapper.updateById(appUser);
        // 发送广播消息,通知下游
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser, appUserDTO);
        appUserDTO.setId(appUser.getId());
        try {
            rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, "", appUserDTO);
        } catch (Exception exception) {
            log.error("编辑用户发送消息失败", exception);
        }
    }


    /**
     * 查询C端用户
     * @param appUserListReqDTO 查询C端用户DTO
     * @return C端用户分页结果
     */
    @Override
    public BasePageDTO<AppUserDTO> getUserList(AppUserListReqDTO appUserListReqDTO) {
        appUserListReqDTO.setPhoneNumber(AESUtil.encryptHex(appUserListReqDTO.getPhoneNumber()));
        BasePageDTO<AppUserDTO> result = new BasePageDTO<>();
        LambdaQueryWrapper<AppUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(appUserListReqDTO.getUserId()!= null,AppUser::getId, appUserListReqDTO.getUserId());
        lambdaQueryWrapper.eq(appUserListReqDTO.getPhoneNumber()!=null,AppUser::getPhoneNumber, appUserListReqDTO.getPhoneNumber());
        lambdaQueryWrapper.eq(appUserListReqDTO.getOpenId()!=null,AppUser::getOpenId, appUserListReqDTO.getOpenId());
        lambdaQueryWrapper.like(appUserListReqDTO.getNickName()!=null,AppUser::getNickName, appUserListReqDTO.getNickName());
        Page<AppUser> page = appUserMapper.selectPage(new Page<>(appUserListReqDTO.getPageNo(), appUserListReqDTO.getPageSize()), lambdaQueryWrapper);
        result.setTotals(Integer.parseInt(String.valueOf(page.getTotal())));
        result.setTotalPages(Integer.parseInt(String.valueOf(page.getPages())));
        List<AppUser> appUserList = page.getRecords();
        List<AppUserDTO> appUserDTOS = BeanCopyUtil.copyListProperties(appUserList, AppUserDTO::new);
        for (AppUserDTO appUserDTO : appUserDTOS) {
            if(!StringUtil.isBlank(appUserDTO.getPhoneNumber())) {
                appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUserDTO.getPhoneNumber()));
            }
        }
        result.setList(appUserDTOS);
        return result;
    }

    /**
     * 根据用户ID获取用户信息
     * @param userId 用户ID
     * @return C端用户DTO
     */
    @Override
    public AppUserDTO findById(Long userId) {
        if (userId == null) {
            return null;
        }
        AppUser appUser = appUserMapper.selectById(userId);
        if (appUser == null) {
            return null;
        }
        // 3 对象转换
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser, appUserDTO);
        appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
        appUserDTO.setId(appUser.getId());
        return appUserDTO;
    }

    /**
     * 根据用户ID列表获取用户列表信息
     * @param userIds 用户ID列表
     * @return C端用户DTO列表
     */
    @Override
    public List<AppUserDTO> getUserList(List<Long> userIds) {
        // 1 对入参进行判空
        if (CollectionUtils.isEmpty(userIds)) {
            return Arrays.asList();
        }
        // 2 查询appUser列表
        List<AppUser> appUserList = appUserMapper.selectBatchIds(userIds);
        return BeanCopyUtil.copyListProperties(appUserList, AppUserDTO::new).stream().filter(Objects::nonNull).toList();
    }
}
